/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lyh.api;

import com.google.protobuf.DescriptorProtos;
import com.lyh.proto.MessageServiceGrpc;
import com.lyh.proto.Query;
import com.lyh.proto.TaskMessage;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.internal.JsonUtil;
import io.grpc.stub.StreamObserver;

/**
 * @author SHOUSHEN.LUAN
 * @since 2023-09-11
 */
public class MessageClient {
    public static void main(String[] args) throws InterruptedException {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8088).usePlaintext().build();
        MessageServiceGrpc.MessageServiceStub stub = MessageServiceGrpc.newStub(channel);
        Query request = Query.newBuilder().setAppKey("Hello, server!").build();
        // 调用服务方法，并接收来自服务端推送的消息
        stub.streamMessage(request, new StreamObserver<TaskMessage>() {
            @Override
            public void onNext(TaskMessage response) {
                System.out.println("接收来自服务端消息: " + response.toString());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("连接服务报错:" + throwable.getMessage());
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("Server closed the stream.");
            }
        });
        // 阻塞线程以等待来自服务端推送的消息
        Thread.sleep(10000);
        System.out.println("--->> done");

        // 关闭gRPC通道
        channel.shutdown();
    }
}
